﻿import {  Injectable }from '@angular/core';
import {Hero}from './hero';
import { Headers, Http }from '@angular/http';
import 'rxjs/add/operator/toPromise';

//数据服务。
@Injectable()
export class HeroService {
    //private heroesUrl = 'app/heroes';
    //http://localhost:4795/hero.aspx
    private heroesUrl = '/app/hero.aspx';
    private headers = new Headers({ 'Content-Type': 'application/json' });
    //private heroesUrl = 'app/heroes';  // URL to web api
    constructor(private http: Http) { }
    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.heroesUrl)
            .toPromise()
            .then(response => {
                return response.json() as Hero[];
            }).catch(this.handleError);
    }
    getHero(id: number): Promise<Hero> {
        return this.getHeroes()
            .then(heroes => heroes.find(hero => hero.id === id));
    }
    delete(id: number): Promise<void> {
        const url = `${this.heroesUrl}?cmd=del&id=${id}`;
        //return this.http.delete(url, { headers: this.headers, body:'' })
        //    .toPromise()
        //    .then(() => null)
        //    .catch(this.handleError);
        return this.http.get(url)
            .toPromise()
            .then(() => null)
            .catch(this.handleError);
    }
    create(name: string): Promise<Hero> {
        const url = `${this.heroesUrl}?cmd=add`;
        var headers1 = new Headers();
        headers1.append('Content-Type', 'application/x-www-form-urlencoded');
        return this.http
            .post(url, 'name='+name, { headers:headers1 })
            .toPromise()
            .then(res => res.json() as Hero)
            .catch(this.handleError);
    }
    update(hero: Hero): Promise<Hero> {
        const url = `${this.heroesUrl}?cmd=update&id=${hero.id}`;
        //return this.http
        //    .put(url, JSON.stringify(hero), { headers: this.headers })
        //    .toPromise()
        //    .then(() => hero)
        //    .catch(this.handleError);
        var headers1 = new Headers();
        headers1.append('Content-Type', 'application/x-www-form-urlencoded');

        let body = "name=" + hero.name;
        return this.http
            .post(url, body, { headers: headers1 })
            .toPromise()
            .then((a) => a.json() as Hero)
            .catch(this.handleError);
    }
    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}